<script setup lang="ts">
    import type { FormInstance, FormValidateCallback } from 'element-plus'
    import type { ModbusSignalPosition } from './type'




    const baseApi = '/modbus-config/modbus-signal-position'

    defineProps<{
        // 禁用表单内的所有组件
        disabled?: boolean
        // 禁用属性列表（只读不可输入）
        disabledProps?: string[]
        // 不可见属性列表（忽略不加载）
        invisibleProps?: string[]
    }>()

    const emit = defineEmits<{
        (e: 'complete', id?: string, isNew?: boolean): void
        (e: 'submitting', submitting: boolean): void
    }>()


    const { initRelatedData, relatedData } = useOption({
        dict: ['modbusFun', 'rw'],
        load: {
            salveConfigIdOptions: {type: 'ModbusSlaveConfig', label: 'name'},
        },
    })

    const {loadData, loading, model} = useDetail<ModbusSignalPosition>(baseApi, {
            readWriteAccess: 'rw',
    })

    const { submitting, submit } = useForm({ baseApi, successCallback: (id, isNew) => emit('complete', id, isNew) })
    watch(submitting, value => emit('submitting', value))

    //  表单
    const formRef = ref<FormInstance>()



    const validate = (callback: FormValidateCallback = (valid: boolean) => !valid && ElMessage.error({ message: '表单校验不通过', grouping: true })) =>
        Promise.all(
            [
                formRef.value,
            ]
                .map(e => e?.validate?.(callback))
                .filter(e => !!e)
        )
            .then((arr: (boolean | undefined)[]) => arr.every(e => e))
            .catch(() => false)

    defineExpose({
        init: (id?: string, refresh = true, initData?: Record<string, unknown>) => {
                // 初始化选项
                initRelatedData()
            if (model.value.id === id && !refresh) return
            // 加载数据
            loadData(id).then(() => {
                if (!id) {
                    if (initData) Object.keys(initData).forEach(key => (model.value[key as keyof ModbusSignalPosition] = initData[key] as any))
                }


            })
        },
        validate,
        getData: async (relatedLabel = false) => {
            const data: Record<string, unknown> = _.cloneDeep(model.value)
            if (!relatedLabel) return data
                                            if ((data.salveConfigId as string)?.length) {
                            let options = relatedData.salveConfigIdOptions
                            data.salveConfigIdLabel = options.find(e => e.value === data.salveConfigId)?.label
                        } else data.salveConfigIdLabel = undefined
                     
                        data.funLabel = relatedData.modbusFunOptions.find(e => e.value === data.fun)
                     
                        data.readWriteAccessLabel = relatedData.rwOptions.find(e => e.value === data.readWriteAccess)

            return data
        },
        submit: () => submit(model.value, formRef.value),
        reset: () => {
            formRef.value?.resetFields()
            model.value.id = void 0
        }
    })



</script>

<template>
    <el-form ref="formRef" v-loading="loading" :model="model" label-width="90px" :disabled="disabled">
        <el-row :gutter="18">
                <el-col v-if="!invisibleProps?.includes('salveConfigCode')" :span="12">
                        <el-form-item prop="salveConfigCode" label="salve配置编码">
                                <el-input
                                        v-model="model.salveConfigCode"
                                        
                                        :disabled="disabledProps?.includes('salveConfigCode')"
                                        clearable
                                />
                        </el-form-item>
                </el-col>
                <el-col v-if="!invisibleProps?.includes('salveConfigId')" :span="12">
                        <el-form-item prop="salveConfigId" label="salve配置Id">
                                    <el-select
                                        v-model="model.salveConfigId"
                                        
                                        :disabled="disabledProps?.includes('salveConfigId')"
                                        filterable
                                        clearable
                                    >
                                        <el-option v-for="item in relatedData.salveConfigIdOptions" :key="item.value"
                                                   v-bind="item">
                                            <div v-if="typeof item.ext === 'string'" class="option">
                                                {{ item.label }}
                                                <span class="ext">（{{ item.ext }}）</span>
                                            </div>
                                        </el-option>
                                    </el-select>
                        </el-form-item>
                </el-col>
                <el-col v-if="!invisibleProps?.includes('salveId')" :span="12">
                        <el-form-item prop="salveId" label="salveId">
                                <el-input-number
                                        v-model="model.salveId"
                                        
                                        :disabled="disabledProps?.includes('salveId')"
                                    step-strictly
                                />
                        </el-form-item>
                </el-col>
                <el-col v-if="!invisibleProps?.includes('name')" :span="12">
                        <el-form-item prop="name" label="名称">
                                <el-input
                                        v-model="model.name"
                                        
                                        :disabled="disabledProps?.includes('name')"
                                        clearable
                                />
                        </el-form-item>
                </el-col>
                <el-col v-if="!invisibleProps?.includes('dataType')" :span="12">
                        <el-form-item prop="dataType" label="数据类型">
                                <el-input
                                        v-model="model.dataType"
                                        
                                        :disabled="disabledProps?.includes('dataType')"
                                        clearable
                                />
                        </el-form-item>
                </el-col>
                <el-col v-if="!invisibleProps?.includes('offset')" :span="12">
                        <el-form-item prop="offset" label="偏移量">
                                <el-input
                                        v-model="model.offset"
                                        
                                        :disabled="disabledProps?.includes('offset')"
                                        clearable
                                />
                        </el-form-item>
                </el-col>
                <el-col v-if="!invisibleProps?.includes('remark')" :span="12">
                        <el-form-item prop="remark" label="备注">
                                <el-input
                                        v-model="model.remark"
                                        
                                        :disabled="disabledProps?.includes('remark')"
                                        clearable
                                />
                        </el-form-item>
                </el-col>
                <el-col v-if="!invisibleProps?.includes('fun')" :span="12">
                        <el-form-item prop="fun" label="功能码">
                                    <el-select
                                            v-model="model.fun"
                                            
                                            :disabled="disabledProps?.includes('fun')"
                                            filterable
                                            clearable
                                    >
                                        <el-option v-for="item in relatedData.modbusFunOptions"
                                                   :key="item.value" v-bind="item"/>
                                    </el-select>
                        </el-form-item>
                </el-col>
                <el-col v-if="!invisibleProps?.includes('readWriteAccess')" :span="12">
                        <el-form-item prop="readWriteAccess" label="读写">
                                    <el-select
                                            v-model="model.readWriteAccess"
                                            
                                            :disabled="disabledProps?.includes('readWriteAccess')"
                                            filterable
                                            clearable
                                    >
                                        <el-option v-for="item in relatedData.rwOptions"
                                                   :key="item.value" v-bind="item"/>
                                    </el-select>
                        </el-form-item>
                </el-col>
        </el-row>
    </el-form>


</template>

<style scoped lang="scss">
    .option {
        display: flex;
        justify-content: space-between;

        .ext {
            font-size: var(--el-font-size-extra-small);
            color: var(--el-text-color-secondary);
        }
    }

</style>